const fs = require('fs')
let tplAxios = {
    getTemplate: function (list, tplName) {
        for (var key in list) {
            var template = require('art-template');
            var text = template(__dirname + '/../tpl/tpl-axios.art', {
                apiList:list[key]
            });
            tplAxios.saveFile(key,text)
        }
    },
    saveFile(key,text){
        fs.mkdir('./api/', (err) => {
            fs.appendFileSync(`./api/${key}.js`, text, function () {
            })
        });
    },
    group(list){
        return list.reduce((pre, item) => {
            pre[item.modelName] = [...pre[item.modelName] || [], item];
            return pre;
        }, {});
    },
    makefile (paths,tplName) {
        let newList = []
        let apiCount = 0
        for (const urlKey in paths) {
            let inputDataItem = paths[urlKey];
            for (const methodTypeKey in inputDataItem) {
                console.log(urlKey,methodTypeKey)
                let inputMethodInfo = inputDataItem[methodTypeKey];
                let moduleName = inputMethodInfo.tags[0];
                let cloneMethodInfo = {};
                cloneMethodInfo.name = moduleName
                cloneMethodInfo.apiUrl = urlKey;
                cloneMethodInfo.methodType = methodTypeKey;
                cloneMethodInfo.methodDesc = inputMethodInfo.summary;
                cloneMethodInfo.methodParameters = tplAxios.collectMethodParametersText(inputMethodInfo.parameters);
                cloneMethodInfo.modelName =`api${tplAxios.getStr(urlKey)[0]}`
                cloneMethodInfo.operationId = tplAxios.replaceStr(inputMethodInfo.operationId
                )
                newList.push(cloneMethodInfo)
                apiCount++
            }
        }
        let group = tplAxios.group(newList);
        tplAxios.getTemplate(group)
        console.log(`生成了${apiCount}个接口`)
    },
    replaceStr(str){
        let text = str;
        text = text.replace('GET', '');
        text = text.replace('POST', '');
        text = text.replace('DELETE', '');
        text = text.replace('PUT', '');
        return text;
    },
    collectMethodParametersText(parameters) {
        let text = '';
        if (!parameters || !parameters.length) {
            return text;
        }
        parameters.forEach (parameter => {
            text += `${parameter.name}-${parameter.description}${!!parameter.required ? ':t' : ''}  `
        });
        return text;
    },
    replaceStr(str){ // 正则法
        str = str.toLowerCase();
        var reg = /\b(\w)|\s(\w)/g; //  \b判断边界\s判断空格
        return str.replace(reg,function(m){
            return m.toUpperCase()
        });
    },
    /**
     * 字符转数组
     */
    getStr(str) {
        list = str.split('/').filter(item => item);
        list.forEach((item, i) => {
            list[i] = this.replaceStr(item)
        })
        return list;
    }
}
module.exports = tplAxios
